/*
 * @Description:
 * @Author: zhangqj
 * @Date: 2021-01-27 16:14:43
 * @LastEditors: zhangqj
 * @LastEditTime: 2021-01-27 17:47:17
 */
export default class drawCircle {
  constructor(_options) {
    this._options = _options
  }
  draw() {
    const options = this._options || {} // 获取或定义options对象;
    options.angle = options.angle || 1 // 定义默认角度1为360度(角度范围 0-1);
    options.color = options.color || '#fff' // 定义默认颜色（包括字体和边框颜色）;
    options.lineWidth = options.lineWidth || 5 // 定义默认圆描边的宽度;
    options.lineCap = options.lineCap || 'square' // 定义描边的样式，默认为直角边，round 为圆角

    const oBoxOne = document.getElementById(options.id)
    const sCenter = oBoxOne.width / 2 // 获取canvas元素的中心点;
    const ctx = oBoxOne.getContext('2d')
    const nBegin = Math.PI / 2 // 定义起始角度;
    const nEnd = Math.PI * 2 // 定义结束角度;

    ctx.textAlign = 'center' // 定义字体居中;
    ctx.font = 'normal normal bold 12px Arial' // 定义字体加粗大小字体样式;
    ctx.fillStyle = options.color
    ctx.fillText(options.text, sCenter, sCenter + 4) // 设置填充文字;
    ctx.lineCap = options.lineCap
    ctx.strokeStyle = options.color
    ctx.lineWidth = 3

    ctx.beginPath() // 设置起始路径，这段绘制360度背景;
    ctx.strokeStyle = '#E7E9F4'
    ctx.arc(sCenter, sCenter, sCenter - options.lineWidth, -nBegin, nEnd, false)
    ctx.stroke()

    const imd = ctx.getImageData(0, 0, 240, 240)
    function draw(current) {
      ctx.lineWidth = 5
      ctx.putImageData(imd, 0, 0)
      ctx.beginPath()
      ctx.strokeStyle = options.color
      ctx.arc(
        sCenter,
        sCenter,
        sCenter - options.lineWidth,
        -nBegin,
        nEnd * current - nBegin,
        false
      )
      ctx.stroke()
    }

    function loadCanvas(angle) {
      // 该函数循环绘制指定角度，实现加载动画;
      draw(options.angle)
    }
    loadCanvas(options.angle) // 载入百度比角度  0-1 范围;
  }

  clearCanvas(id) {
    const c = document.getElementById(id)
    const cxt = c.getContext('2d')
    if (c) {
      cxt.clearRect(0, 0, c.width, c.height)
    }
  }
}
